package ca.starfarer.kobold.dao.sqlite;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

class Helper {

    static void dropTable(Statement statement, String tableName) throws SQLException {
        statement.executeUpdate("drop table if exists " + tableName);
    }

    static void createTable(Statement statement, String tableName, String[] columnNames) throws SQLException {
        StringBuffer buf = new StringBuffer();

        buf.append("create table ").append(tableName).append(" ( Id integer primary key asc");

        for (String column : columnNames) {
            buf.append(", ").append(column);
        }

        buf.append(")");

        statement.executeUpdate(buf.toString());
    }

    static Long insert(Statement statement, String tableName, String[] columnNames, Object... values) throws SQLException {
        StringBuffer buf = new StringBuffer();

        buf.append("insert into ").append(tableName).append(" (");

        for (String column : columnNames) {
            buf.append(column).append(", ");
        }
        buf.setLength(buf.length() - 2);

        buf.append(") values (");
        for (Object value : values) {
            buf.append(escape(value)).append(", ");
        }
        buf.setLength(buf.length() - 2);

        buf.append(")");

        statement.executeUpdate(buf.toString());

        ResultSet resultSet = statement.getGeneratedKeys();
        resultSet.next();
        return resultSet.getLong(1);
    }

    static void update(Statement statement, String tableName, String[] columnNames, Long id, Object... values) throws SQLException {
        StringBuffer buf = new StringBuffer();

        buf.append("update ").append(tableName).append(" set ");

        for (int i = 0; i < columnNames.length; i++) {
            buf.append(columnNames[i]).append(" = ").append(escape(values[i])).append(", ");
        }
        buf.setLength(buf.length() - 2);

        buf.append(" where Id = ").append(escape(id));

        statement.executeUpdate(buf.toString());
    }

    static String escape(Object value) {
        if (value instanceof String) {
            return "\"" + value + "\"";
        }
        return String.valueOf(value);
    }

    /** Hidden constructor */
    private Helper() { }
}
